class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def longestConsecutive(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.max = -1

        def search(node):
            left_a_count = 1
            left_d_count = 1
            right_a_count = 1
            right_d_count = 1
            if node.left:
                left_a_count, left_d_count, left_val = search(node.left)
                if node.val == left_val + 1:
                    left_a_count += 1
                    left_d_count = 1
                else:
                    if node.val == left_val - 1:
                        left_d_count += 1
                        left_a_count = 1
                    else:
                        left_a_count = 1
                        left_d_count = 1
            if node.right:
                right_a_count, right_d_count, right_val = search(node.right)
                if node.val == right_val + 1:
                    right_a_count += 1
                    right_d_count = 1
                else:
                    if node.val == right_val - 1:
                        right_d_count += 1
                        right_a_count = 1
                    else:
                        right_a_count = 1
                        right_d_count = 1
            self.max = max(self.max, left_a_count + right_d_count - 1, left_d_count + right_a_count - 1)
            return max(left_a_count, right_a_count), max(left_d_count, right_d_count), node.val

        search(root)
        return self.max
